<?php

namespace App\Http\Controllers;

use App\Models\FavModel;
use App\Models\GoodsFavViewModel;
use App\Models\GoodsPicAllModel;
use App\Models\GoodsPicModel;
use App\Models\GoodsPicPrimaryModel;
use App\Models\GoodsPicPrimaryViewModel;
use App\Models\SupplyModel;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;

class PCApiController extends Controller
{
    /**
     * 获取总数
     * @param Request $request
     * @return Application|Response|\Illuminate\Contracts\Foundation\Application|ResponseFactory
     */
    public function total(Request $request): Application|Response|\Illuminate\Contracts\Foundation\Application|ResponseFactory
    {
        $params = $this->parseParams($request);
        $data = match (intval($params['v2'])) {
            6 => $this->search($params['v0'], $params['v1'], $params['v2'], $params['v3'], $params['v4'], $params['v5'], $params['v6']),
            7 => $this->getTypePic($params['v0'], $params['v3'], $params['v4'], $params['v6']),
            8 => $this->getSupplyPic($params['v0'], $params['v3'], $params['v4'], $params['v6']),
            9 => $this->getFavPic($params['v6'], $params['v2'], $params['v3'], $params['v4']),
            default => $this->getPics($params['v0'], $params['v1'], $params['v2'], $params['v3'], $params['v4']),
        };
        return response($data);
    }

    /**
     * 获取列表数据
     * @param Request $request
     * @return Response|ResponseFactory
     */
    public function getList(Request $request): Response|ResponseFactory
    {
        $params = $this->parseParams($request);
        $data = match (intval($params['v2'])) {
            6 => $this->search($params['v0'], $params['v1'], $params['v2'], $params['v3'], $params['v4'], $params['v5'], $params['v6'], false),
            7 => $this->getTypePic($params['v0'], $params['v3'], $params['v4'], $params['v6'], false),
            8 => $this->getSupplyPic($params['v0'], $params['v3'], $params['v4'], $params['v6'], false),
            9 => $this->getFavPic($params['v6'], $params['v2'], $params['v3'], $params['v4'], false),
            default => $this->getPics($params['v0'], $params['v1'], $params['v2'], $params['v3'], $params['v4'], false),
        };
        $ids = [];
        $sids = [];
        // 一次遍历获取id
        foreach ($data as $v) {
            if ($v->skuFlag)
                continue;
            $ids[] = $v->ID;
            $sids[] = $v->SID;
        }
        $picMap = GoodsPicPrimaryModel::whereIn('ID', $ids)->select('ali_url', 'ID')->get();
        $supplyMap = SupplyModel::whereIn('ID', $sids)->select('shipping_type', 'ID')->get();
        $picDict = [];
        $supplyDict = [];
        $newData = [];
        foreach ($picMap as $v) {
            $picDict[$v->ID] = $v->ali_url;
        }
        foreach ($supplyMap as $v) {
            $supplyDict[$v->ID] = $v->shipping_type;
        }
        // 二次遍历注入数据
        foreach ($data as $v) {
            $picAliUrl = $picDict[$v->ID] ?? '';
            $supplyShippingType = $supplyDict[$v->SID] ?? 3;
            if ($supplyShippingType >= 2 && !empty($picAliUrl))
                $v->aliFlag = 1;
            else
                $v->aliFlag = 0;
            $newData[] = $v;
        }
        return response($newData);
    }

    /**
     * 获取图片列表或总数
     * @param $pid
     * @param $v1
     * @param $v2
     * @param $v3
     * @param $v4
     * @param bool $sum
     * @return Collection|int
     */
    private function getPics($pid, $v1, $v2, $v3, $v4, bool $sum = true): int|Collection
    {
        $area_ids = $this->getAreaId($v1);
        $field = $this->getQueryField($v1, $v2);
        $order = $this->getOrderField($v1, $v2);
        if ($pid === '0')
            $model = GoodsPicPrimaryViewModel::where('PStatus', 0)->where('PID', 0);
        else
            $model = GoodsPicAllModel::where('PStatus', 0)->where('PID', $pid)->orWhere('ID', $pid);
        if (is_array($area_ids))
            $model = $model->whereIn('AreaID', $area_ids);
        else
            $model = $model->where('AreaID', $area_ids);
        if ($field)
            $model = $model->where($field, 1);
        if ($sum)
            $data = $model->count('ID');
        else
            $data = $model->orderBy($order, 'desc')->orderBy('ID', 'desc')->offset($v3)->limit($v4)->get();
        return $data;
    }

    /**
     * 查询
     * @param $pid
     * @param $v1
     * @param $v2
     * @param $v3
     * @param $v4
     * @param $v5
     * @param $v6
     * @param bool $sum
     * @return Collection|int
     */
    private function search($pid, $v1, $v2, $v3, $v4, $v5, $v6, bool $sum = true): int|Collection
    {
		//Log::debug('执行搜索');
        $area_ids = $this->getAreaId($v1);
        if ($pid) {
            $model = GoodsPicAllModel::where('PStatus', 0)->where('PID', $pid)->orWhere('ID', $pid);
            if ($sum)
                return $model->count('ID');
            return $model->orderBy('ID', 'desc')->orderBy('PName', 'desc')->offset($v3)->limit($v4)->get();
        }
        $model = GoodsPicPrimaryViewModel::where('PStatus', 0)->where('PID', 0);
        if (is_array($area_ids))
            $model = $model->whereIn('AreaID', $area_ids);
        else
            $model = $model->where('AreaID', $area_ids);
        if (is_numeric($v6) && $this->notEqualPName($v6))
            $model = $model->whereRaw('instr(ToySn, "'. $v6 .'") > 0');
        else
            $model = $model->whereRaw('(instr(PName, "'.$v6.'") > 0 OR instr(SName, "'.$v6.'"))');
        if ($sum)
            $data = $model->count('ID');
        else
            $data = $model->orderBy('AllID', 'desc')->orderBy('ITime', 'desc')->offset($v3)->limit($v4)->get();
        return $data;
    }

    /**
     * 获取类别图片
     * @param $pid
     * @param $v3
     * @param $v4
     * @param $v6
     * @param bool $sum
     * @return Collection|int
     */
    private function getTypePic($pid, $v3, $v4, $v6, bool $sum = true): int|Collection
    {
        $model = GoodsPicAllModel::where('PStatus', 0);
        if ($pid)
            $model = $model->where('PID', $pid)->orWhere('ID', $pid);
        else
            $model = GoodsPicPrimaryViewModel::where('PStatus', 0)->where('PID', 0)->where('Type', 'like', '%|'.$v6.'|%');
        if ($sum)
            $data = $model->count('ID');
        else
            $data = $model->orderBy('ID', 'desc')->orderBy('PName', 'desc')->offset($v3)->limit($v4)->get();
        return $data;
    }

    /**
     * 获取商家图片
     * @param $pid
     * @param $v3
     * @param $v4
     * @param $v6
     * @param bool $sum
     * @return Collection|int
     */
    private function getSupplyPic($pid, $v3, $v4, $v6, bool $sum = true): int|Collection
    {
        if ($pid)
            $model = GoodsPicAllModel::where('PStatus', 0)->where('PID', $pid)->orWhere('ID', $pid);
        else
            $model = GoodsPicPrimaryViewModel::where('PStatus', 0)->where('PID', 0)->where('SID', $v6);
        if ($sum)
            $data = $model->count('ID');
        else
            $data = $model->orderBy('AllID', 'desc')->orderBy('ITime', 'desc')->offset($v3)->limit($v4)->get();
        return $data;
    }

    /**
     * 添加收藏
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|ResponseFactory|Application|Response
     */
    public function addFavourite(Request $request): Application|Response|\Illuminate\Contracts\Foundation\Application|ResponseFactory
    {
        $params = $this->parseParams($request);
        $data = FavModel::where('CID', $params['v1'])->where('PID', $params['v2'])->first();
        if (!$data) {
            $data = ['CID' => $params['v1'], 'PID' => $params['v2'], 'CTime' => date('Y-m-d H:i:s')];
            FavModel::create($data);
        }
        return response(1);
    }

    /**
     * 删除收藏
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|ResponseFactory|Application|Response
     */
    public function delFav(Request $request): Application|Response|\Illuminate\Contracts\Foundation\Application|ResponseFactory
    {
        $params = $this->parseParams($request);
        FavModel::where('CID', $params['v1'])->where('PID', $params['v2'])->delete();
        return response(1);
    }

    /**
     * 查询收藏
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|ResponseFactory|Application|Response
     */
    public function queryFav(Request $request): Application|Response|\Illuminate\Contracts\Foundation\Application|ResponseFactory
    {
        $params = $this->parseParams($request);
        $data = FavModel::where('CID', $params['v1'])->where('PID', $params['v2'])->first();
        return response($data ? 1 : 0);
    }

    /**
     * 获取商品详情
     * @param Request $request
     * @return ResponseFactory|Response
     */
    public function getPicDetail(Request $request): Response|ResponseFactory
    {
        $params = $this->parseParams($request);
        $data = GoodsPicModel::where('PStatus', 0)->where('PID', $params['v0'])->orWhere('ID', $params['v0'])->get()->toArray();
        if ($data) {
            $ids = [];
            foreach ($data as $v) {
                $ids[] = $v['ID'];
            }
            array_multisort($ids, SORT_DESC, $data);
        }
        $offset = $params['v3'] ?: 0;
        $limit = $params['v4'] ?: 21;
        $newData = array_slice($data, $offset, $limit);
        return response($newData);
    }

    /**
     * 获取收藏产品
     * @param $v6
     * @param $v2
     * @param $v3
     * @param $v4
     * @param bool $sum
     * @return Collection|int
     */
    private function getFavPic($v6, $v2, $v3, $v4, bool $sum = true): int|Collection
    {
        $Model = GoodsFavViewModel::where('CID', $v6);
        if ($sum)
            return $Model->count('ID');
        return $Model->orderBy('CTime', 'desc')->offset($v3)->limit($v4)->get();
    }

    /**
     * 更新
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|ResponseFactory|Application|Response
     */
    public function updatePicInfo(Request $request): Application|Response|\Illuminate\Contracts\Foundation\Application|ResponseFactory
    {
        $params = $this->parseParams($request);
        GoodsPicModel::where('ID', $params['v1'])->update(['FName' => $params['v2']]);
        return response(1);
    }

    /**
     * 获取地区范围
     * @param $v1
     * @return array|int
     */
    protected function getAreaId($v1): array|int
    {
		$v1 = intval($v1);
        $area = match ($v1) {
            1 => [1, 3, 4],
            2 => [2, 3],
            4 => 4,
            default => [1, 2, 3, 4],
        };
        //Log::debug('结果:', is_array($area) ? $area : [$area]);
        return $area;
    }

    /**
     * 获取查询字段
     * @param $v1
     * @param $v2
     * @return string|null
     */
    protected function getQueryField($v1, $v2): ?string
    {
        if ($v1 === '1' && $v2 === '1')
            return 'IsRecommend';
        if ($v1 === '1' && $v2 === '2')
            return 'IsNew';
        if ($v1 === '1' && $v2 === '4')
            return 'IsRight';
        if ($v1 === '2' && $v2 === '1')
            return 'IsRecommend1';
        if ($v1 === '2' && $v2 === '2')
            return 'IsNew1';
        if ($v1 === '2' && $v2 === '4')
            return 'IsRight';
        if ($v1 === '3' && $v2 === '1')
            return 'IsRecommend2';
        if ($v1 === '3' && $v2 === '2')
            return 'IsNew2';
        if ($v1 === '3' && $v2 === '4')
            return 'IsRight';
        // 新增
        if ($v1 === '4' && $v2 === '1')
            return 'IsRecommend2';
        if ($v1 === '4' && $v2 === '2')
            return 'IsNew2';
        if ($v1 === '4' && $v2 === '4')
            return 'IsRight';
        if ($v2 === '5')
            return 'IsB';
        return NULL;
    }

    /**
     * 获取排序字段
     * @param $v1
     * @param $v2
     * @return string
     */
    protected function getOrderField($v1, $v2): string
    {
        if ($v2 === '5' || $v2 === '3')
            return 'ITime';
        if ($v1 === '1' && $v2 === '1')
            return 'RecommendID';
        if ($v1 === '1' && $v2 === '2')
            return 'NewID';
        if ($v1 === '1' && $v2 === '4')
            return 'RightID';
        if ($v1 === '2' && $v2 === '1')
            return 'RecommendID1';
        if ($v1 === '2' && $v2 === '2')
            return 'NewID1';
        if ($v1 === '2' && $v2 === '4')
            return 'RightID1';
        if ($v1 === '3' && $v2 === '1')
            return 'RecommendID2';
        if ($v1 === '3' && $v2 === '2')
            return 'NewID2';
        if ($v1 === '3' && $v2 === '4')
            return 'RightID2';
        // 新增
        if ($v1 === '4' && $v2 === '1')
            return 'RecommendID2';
        if ($v1 === '4' && $v2 === '2')
            return 'NewID2';
        if ($v1 === '4' && $v2 === '4')
            return 'RightID2';
        return 'ITime';
    }

    /**
     * 格式化传值
     * @param $request
     * @return array
     */
    protected function parseParams($request): array
    {
        $params['v0'] = $request->input('v0', 0);
        $params['v1'] = $request->input('v1', 0);
        $params['v2'] = $request->input('v2', 0);
        $params['v3'] = $request->input('v3', 0);
        $params['v4'] = $request->input('v4', 0);
        $params['v5'] = $request->input('v5', 0);
        $params['v6'] = $request->input('v6', 0);
        return $params;
    }

    /**
     * 验证是否存在
     * @param $no
     * @return int
     */
    protected function notEqualPName($no): int
    {
        if(strlen($no) < 6)
            return 1;
        $products = GoodsPicPrimaryModel:: where('SID', 3)->where('PName', 'like', '%SN%')->select(['PName'])->get();
        $reg='/(\d{6}(\.\d+)?)/is';
        $except = [];
        foreach($products as $p) {
            preg_match_all($reg, $p->PName, $result);
            if (isset($result[1][0])) {
                $except[] = $result[1][0];
            }
        }
        return in_array($no, $except) ? 0 : 1;
    }
}
